package org.ddd.productdemo.domaindriven.infrastructure.adapter.outgoing.persistence;

import org.ddd.productdemo.domaindriven.domain.model.aggregate.Order;
import org.ddd.productdemo.domaindriven.domain.model.aggregate.OrderId;
import org.ddd.productdemo.domaindriven.domain.model.entity.CustomerId;
import org.ddd.productdemo.domaindriven.domain.repository.OrderRepository;
import org.ddd.productdemo.domaindriven.infrastructure.adapter.outgoing.persistence.entity.OrderJpaEntity;
import org.ddd.productdemo.domaindriven.infrastructure.adapter.outgoing.persistence.repository.OrderJpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Repository
public class OrderRepositoryAdapter implements OrderRepository {

    private final OrderJpaRepository jpaRepository;

    public OrderRepositoryAdapter(OrderJpaRepository jpaRepository) {
        this.jpaRepository = jpaRepository;
    }

    @Override
    public Optional<Order> findById(OrderId id) {
        return jpaRepository.findById(id.getValue())
                .map(this::mapToDomain);
    }

    @Override
    public Order save(Order order) {
        OrderJpaEntity entity = mapToJpaEntity(order);
        OrderJpaEntity savedEntity = jpaRepository.save(entity);
        return mapToDomain(savedEntity);
    }

    @Override
    public void delete(OrderId id) {
        jpaRepository.deleteById(id.getValue());
    }

    @Override
    public List<Order> findByCustomerId(CustomerId customerId) {
        return jpaRepository.findByCustomerId(customerId.getValue()).stream()
                .map(this::mapToDomain)
                .collect(Collectors.toList());
    }

    private Order mapToDomain(OrderJpaEntity entity) {
        // 映射逻辑
        CustomerId customerId = new CustomerId(entity.getCustomerId());
        Order order = new Order(customerId);

        return order;
    }

    private OrderJpaEntity mapToJpaEntity(Order order) {
        // 映射逻辑
        OrderJpaEntity orderJpaEntity = new OrderJpaEntity();


        return orderJpaEntity;
    }
}
